<?php

namespace App\Http\Controllers\common;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class WechatController extends Controller
{
    static protected $appid = 'wxf945888dccd4b1cf';
    static protected $app_secret = '6d2aef84cc88bf81f96006d1f4bf7b1e';
    static protected $token = 'weixin';
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function navbar()
    {
        $echoStr = $_GET["echostr"];
        if(self::checkSignature()){
            echo $echoStr;
        }else{
            $result = $this->tonavbar();
            var_dump($result);
        }
    }
   
    // 设置菜单按钮
    public function tonavbar()
    {
        $access = self::wechat_token();
        $jsonmenu = '{
            "button":[
                {
                    "type":"view",
                    "name":"内部OA",
                    "url":"http://wap.iqykj.com"
                },
                {
                    "type":"view",
                    "name":"布撤防",
                    "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid='.self::$appid.'&redirect_uri=http%3a%2f%2fwap.iqykj.com%2fhome%2fweixin%2findex&response_type=code&scope=snsapi_base&state=123#wechat_redirect"
                }
            ]
        }';
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access;
        $result = self::topost($url, $jsonmenu);
        return $result;
    }
    // 删除菜单(全部删除)
    public function del_navbar()
    {
        $access = self::wechat_token();
        $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$access;
        $res = self::toget($url);
        return $res;
    }



    // 回复消息
    public function reply()
    {
        header('Content-type:text');
        // 接受用户输入的信息
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        // 接收用户的信息
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $fromUsername = $postObj->FromUserName;//谁发的(用户id)
        $toUsername = $postObj->ToUserName; //发送给谁(公众号id)
        $msg = $postObj->MsgType; //发送给谁(公众号id)
        $result = $this->tonavbar();
        $keyword = trim($postObj->Content);
        if($keyword=="消息模板"){
            $pushmsg = self::wechat_pushmsg();
            $str = '<xml>
                <ToUserName><![CDATA['.$fromUsername.']]></ToUserName>
                <FromUserName><![CDATA['.$toUsername.']]></FromUserName>
                <CreateTime>'.time().'</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA['.$pushmsg.']]></Content>
            </xml>';
            echo $str;
        }else{
            $str = '<xml>
                <ToUserName><![CDATA['.$fromUsername.']]></ToUserName>
                <FromUserName><![CDATA['.$toUsername.']]></FromUserName>
                <CreateTime>'.time().'</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[暂无此功能]]></Content>
            </xml>';
            echo $str;
        }
    }

    static public function wechat_token(){
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.self::$appid.'&secret='.self::$app_secret;
        $jsoninfo = self::toget($url);
        $res = json_decode($jsoninfo, true);
        return $res['access_token'];
    }

    // 发送一个get请求, $url 发送地址
    static public function toget($url)
    {
        // // 初始化操作
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    // 发送一个post请求,$data 参数
    static private function topost($url, $data)
    {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            if (!empty($data)){
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
    }

    // 普通接口token验证 
    static private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $access =self::$token;
        $tmpArr = array($access, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if($tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }
    /**
    * @return access
    * access['
    *   access_token    string  网页授权接口调用凭证,注意：此access_token与基础支持的access_token不同
    *   expires_in      int     access_token接口调用凭证超时时间，单位（秒）
    *   refresh_token   string  用户刷新access_token
    *   openid          string  用户唯一标识，请注意，在未关注公众号时，用户访问公众号的网页，也会产生一个用户和公众号唯一的OpenID
    *   scope           string  用户授权的作用域，使用逗号（,）分隔
    */
    static public function codetojson($code)
    {
        $weixin =  file_get_contents('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.self::$appid.'&secret='.self::$app_secret.'&code='.$code.'&grant_type=authorization_code');

        $codetojson = json_decode($weixin,true);
        return $codetojson;
    }

    // 调用消息模板,进行微信消息推送
    static public function wechat_pushmsg($openid,$keyword)
    {
        $template = array(
            "touser" => $openid,
            "template_id" => "Z-jJjen2sGFmpAVZgWm3QM_BvF4ysvHo0_ATs9TyzQE",
            // "url" => "#",
            "topcolor" => "#CC0000",
            "data" => array(
                "first" => array(
                    // "value" => $keyword['first'],
                    "value" => $keyword['remark'],
                    "color" => "#CC0000"
                ),
                "keyword1" => array(
                    // "value" => $keyword['keyword1'],
                    "value" => $keyword['first'],
                    "color" => "#3366CC"
                ),
                "keyword2" => array(
                    "value" => $keyword['keyword2'],
                    "color" => "#173177"
                ),
                "keyword3" => array(
                    "value" => date("Y年m月d日 H:i",time()),
                    "color" => "#173177"
                ),
                "remark" => array(
                    // "value" => $keyword['remark'],
                    "value" => "请您及时检查并处置！",
                    "color" => "#173177"
                )
            )
        );
        $data = json_encode($template);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".self::wechat_token();
        $getjson = self::topost($url,$data);
        return $getjson;
    }
}